from models import Account
from utils import auth
from bean import RegisterParam
from utils import utils
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes
from .enterprise_service import EnterpriseService
from .enterprise_account_service import EnterpriseAccountService


class AccountService:

    def __init__(self):
        pass

    @classmethod
    async def register(cls, param: RegisterParam):
        passd = auth.get_password_hash(param.password)
        uid = utils.get_uid()
        data_dict = {
            "create_user": uid,
            "update_user": uid,
            "uid": uid,
            "nickname": param.mobile,
            "name": param.mobile,
            "mobile": param.mobile,
            "password": passd
        }

        await Account(**data_dict).save()

    @classmethod
    async def login(cls, param: RegisterParam):
        account: Account = await Account.get_or_none(mobile=param.mobile)

        if not auth.verify_password(param.password, account.password):
            return "error"

        access_token = auth.create_access_token(await account.to_jwt_dict())
        return {"access_token": access_token, "token_type": "bearer"}

    @classmethod
    async def token(cls, param: OAuth2PasswordRequestForm):
        account: Account = await Account.get_or_none(mobile=param.username)

        if not auth.verify_password(param.password, account.password):
            return "error"

        access_token = auth.create_access_token(await account.to_jwt_dict())
        return {"access_token": access_token, "token_type": "bearer"}

    @classmethod
    async def register_by_mobile(cls, mobile):

        acc = await Account.get_or_none(mobile=mobile)
        if acc is not None:
            return {"message": "mobile exist"}

        def_passwd = utils.get_default_password()
        passd = auth.get_password_hash(def_passwd)
        uid = utils.get_uid()
        data_dict = {
            "create_user": uid,
            "update_user": uid,
            "uid": uid,
            "nickname": mobile,
            "name": mobile,
            "mobile": mobile,
            "password": passd
        }
        await Account(**data_dict).save()
        enterprise_uid = await EnterpriseService.insert(mobile, uid)
        await EnterpriseAccountService.insert(uid, enterprise_uid, "0")
        return {"account": mobile, "password": def_passwd}
